{include file='edit.tpl'}

<div id='categories'></div>

<div id='attributes'></div>

{literal}
<script id='attributes_tpl' type="text/x-jsmart-tmpl">
	<table class='params'>
		{foreach $attributes as $attr}
		<tr>
			<td>{$attr.name}</td>
			<td class=v>
			{if $attr.isList}
				<select name='attributes[{$attr.id}]'>
					<option value=''></option>
					{foreach $attr.allowedValues as $v}
						<option value='{$v[0]}' {if $v[0]==$values[$attr.id].value}selected{/if}>{$v[1]}</option>
					{/foreach}
				</select>
			{else}
				<input type=text name='attributes[{$attr.id}]' value='{$values[$attr.id].value|default:''}' />
			{/if}
			</td>
		</tr>
		{/foreach}
	</table>
</script>
{/literal}

<script>
	createTabs = function() {
		addTab('categories','Категории');
		addTab('attributes','Свойства');
	};
	
	var catsChanged = true;
	
	$( function() {
		setFirstTabTitle('Товар');
		
		call('shop.getCategories').done( function (items) { 
			catTree = new jPineCheck($('#categories')[0], items);
			catTree.onCheck = function(item) {
				catsChanged = true;
				var catIDs = this.getPropertyOfChecked('id');
				$('#categories input[type=hidden]').remove();
				for (var i=0; i<catIDs.length; ++i) {
					$('#categories').append('<input type=hidden name="category[]" value="'+catIDs[i]+'">');
				}
			}
			catTree.expandAll();
			if ('id' in k) {
				call('shop.getProduct', { 'id': k['id'] } ).done( function(product) {
					for (var i=0; i<product.groups.length; ++i) {
						var catId = product.groups[i];
						catTree.forEach(function(item) {
							if (item.properties.id == catId) {
								catTree.onClick(item);
								return false;
							}
						} );
					}
				} );
			}
		} );
		
	
		$('#tabs').bind('tabsshow', function(event, ui) {
			if (ui.panel.id == 'attributes' && catsChanged) {
				$('#attributes table').remove();
				var catIDs = catTree.getPropertyOfChecked('id');
				if (catIDs.length) {
					$.when(
						call('shop.getCategoryAttributes', { 'catId':catIDs } ),
						call('shop.getProduct', { 'id':('id' in k) ? k['id'] : 0 } )
					).done( function (data1,data2) {
						$('#attributes').html( $('#attributes_tpl').html().fetch( { 'attributes':data1[0], 'values':data2[0].attributes } ) );
						$('table.params input:text, select').on( {
							'focus': function(e) { $(e.target).closest('tr').addClass('active'); },
							'blur': function(e) { $(e.target).closest('tr').removeClass('active'); }
						} );
					} );
				}
				catsChanged = false;
			}
		});
	} );
</script>